﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Emerson.Storage.Service.Interface;
using Emerson.Storage.Entities;
using System.Web.Services;
using System.Web.Script.Services;

namespace WorkstationDashboard
{
    public partial class ContentGroup : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BuildTreeView();
                groupId.Value = Request.Params["id"];
                Utility.SelectNode(Master.WorkstationTreeView, NodeType.Group, int.Parse(groupId.Value));
                SetGroupInfo();
            }
        }

        private void SetGroupInfo()
        {
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();
            int id = int.Parse(groupId.Value);
            Group group = wsService.GetGroup(id);
            int okCount = 0;
            int disCount = 0;

            foreach (Workstation w in group.Workstation)
            {
                if (w.IsConnected)
                    okCount++;
                else
                    disCount++;
            }

            okWorkstationCount.Text = okCount.ToString();
            disconnectedWorkstationCount.Text = disCount.ToString();

            groupName.Text = group.Name;
        }

        private void BuildTreeView()
        {
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();

            WorkstationRoot wkRoot = wsService.GetWorkstationRoot();
            TreeNode treeRoot = Utility.BuildTreeFromWorkstationRoot(wkRoot);
            Master.WorkstationTreeView.Nodes.Clear();
            Master.WorkstationTreeView.Nodes.Add(treeRoot);
        }

        [WebMethod]
        [ScriptMethod]
        public static void RemoveGroup(string groupIdString)
        {
            IWorkstationService wsService = ServiceHelper.GetService<IWorkstationService>();
            int groupId = int.Parse(groupIdString);
            wsService.DeleteGroup(groupId);
        }
    }
}
